﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using log4net;
using McsUtility;
using System.Threading;

namespace MinerManager.Forms
{
	public partial class UserRegister : DevExpress.XtraEditors.XtraForm
	{
		ILog logger = LogManager.GetLogger(typeof(Program));
		private Common.AgentComponent Agent = null;

		private List<McsUtility.Models.StaffModel> infosStaff = new List<McsUtility.Models.StaffModel>();

		public UserRegister(Common.AgentComponent agent)
		{
			InitializeComponent();
			this.Agent = agent;
		}

		#region 窗体事件

		private void UserRegister_Load(object sender, EventArgs e)
		{
			this.Agent.OnNodeServerMinerManagerGetStaffs += new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCodeReceive);
			//this.Agent.OnGetRegSmsCodeReceive += new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCode);
			//this.Agent.OnManagerRegisterReceive += new EventHandler<ByteEventArgs>(Agent_OnManagerRegister);

			//连接服务器
			if (!this.Agent.IsStarted)
			{
				Common.ConnectionServer conn = new Common.ConnectionServer(this.Agent);
				conn.Connection();
			}

			byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerGetStaffs, "");
			this.Agent.AgentSend(bytes);
		}

		private void UserRegister_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.Agent.OnNodeServerMinerManagerGetStaffs -= new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCodeReceive);
			//this.Agent.OnGetRegSmsCodeReceive -= new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCode);
			//this.Agent.OnManagerRegisterReceive -= new EventHandler<ByteEventArgs>(Agent_OnManagerRegister);
		}

		#endregion

		#region Agent事件

		private void Agent_OnGetRegSmsCodeReceive(object sender, ByteEventArgs e)
		{
			infosStaff = ProtocolHelper.ReadPackageBody<List<McsUtility.Models.StaffModel>>(e.Bytes);

			//获取默认客户经理
			string staffId = System.Configuration.ConfigurationManager.AppSettings["StaffId"];
			if (string.IsNullOrWhiteSpace(staffId))
				staffId = "2";

			//控件操作
			List<ComboboxListItem> items = new List<ComboboxListItem>();
			foreach (McsUtility.Models.StaffModel info in infosStaff)
			{
				items.Add(new ComboboxListItem(info.Name, info.ID.ToString()));
			}
			Utility.Forms.SetComboBoxEdit(this, "ItemStaffs", items, staffId);
		}

		#endregion

		#region void ItemStaffs_SelectedIndexChanged(object sender, EventArgs e)

		private void ItemStaffs_SelectedIndexChanged(object sender, EventArgs e)
		{
			StaffsQQ.Text = infosStaff[ItemStaffs.SelectedIndex].QQ1;
			StaffsWechat.Text = infosStaff[ItemStaffs.SelectedIndex].WeiXin1;
		}

		#endregion

		#region void BtnSendSMSCode_Click(object sender, EventArgs e)

		private void BtnSendSMSCode_Click(object sender, EventArgs e)
		{
			//非法信息检测
			if (string.IsNullOrWhiteSpace(ItemUserName.Text))
			{
				if (MessageBox.Show("请输入手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			if (!ItemUserName.Text.IsMobile())
			{
				if (MessageBox.Show("请输入正确的手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			ItemSMSCode.SelectAll();

			//执行发送验证码
			Thread thread = new Thread(SendSMSCode);
			thread.IsBackground = true;
			thread.Start();
		}

		private void SendSMSCode()
		{
			SetBtnSendSMSCode(false);

			//发送验证码
			McsUtility.Models.ResultModel result = Utility.MinerHttpRequest.SendSMSCode(ItemUserName.Text);
			if (result.success)
			{
				//倒计时
				int second = 60;
				while (true)
				{
					SetBtnSendSMSCode(false, "发送（" + second + "秒）");
					second--;
					Thread.Sleep(1000);

					if (second <= 0)
						break;
				}

				SetBtnSendSMSCode(true, "发送验证码");
			}
			else
			{
				MessageBox.Show("短信发送失败。" + Environment.NewLine + result.message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private delegate void DelegateSetBtnSendSMSCode(bool enable, string text = "");
		private void SetBtnSendSMSCode(bool enable, string text = "")
		{
			if (BtnSendSMSCode.InvokeRequired)
			{
				DelegateSetBtnSendSMSCode d = new DelegateSetBtnSendSMSCode(SetBtnSendSMSCode);
				this.Invoke(d, enable, text);
			}
			else
			{
				BtnSendSMSCode.Enabled = enable;
				BtnSendSMSCode.Text = !string.IsNullOrWhiteSpace(text) ? text : BtnSendSMSCode.Text;
			}
		}

		#endregion

		#region void BtnRegister_Click(object sender, EventArgs e)

		private void BtnRegister_Click(object sender, EventArgs e)
		{
			int smsCode = 0;

			#region 非法信息检测

			if (string.IsNullOrWhiteSpace(ItemUserName.Text))
			{
				if (MessageBox.Show("请输入手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			if (!ItemUserName.Text.IsMobile())
			{
				if (MessageBox.Show("请输入正确的手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemPassword.Text))
			{
				if (MessageBox.Show("请输入登录密码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemPassword.Focus();
					ItemPassword.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemPasswordConfirm.Text))
			{
				if (MessageBox.Show("请输入确认密码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemPasswordConfirm.Focus();
					ItemPasswordConfirm.SelectAll();
				}
				return;
			}

			if (ItemPassword.Text != ItemPasswordConfirm.Text)
			{
				if (MessageBox.Show("登录密码与确认密码应输入相同字符。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemPasswordConfirm.Focus();
					ItemPasswordConfirm.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemName.Text))
			{
				if (MessageBox.Show("请输入姓名。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemName.Focus();
					ItemName.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemSMSCode.Text))
			{
				if (MessageBox.Show("请输入验证码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemSMSCode.Focus();
					ItemSMSCode.SelectAll();
				}
				return;
			}

			if (!int.TryParse(ItemSMSCode.Text, out smsCode))
			{
				if (MessageBox.Show("请输入正确的验证码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemSMSCode.Focus();
					ItemSMSCode.SelectAll();
				}
				return;
			}

			if (((ComboboxListItem)ItemStaffs.SelectedItem).Value.ConvertInt() <= 0)
			{
				if (MessageBox.Show("请选择客户经理。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemStaffs.Focus();
				}
				return;
			}

			#endregion

			McsUtility.Models.ResultModel result = Utility.MinerHttpRequest.Register(
				ItemUserName.Text.Trim(),
				ItemPassword.Text,
				smsCode.ToString(),
				((ComboboxListItem)ItemStaffs.SelectedItem).Value,
				ItemName.Text.Trim(),
				ItemPassQuestion1.Text.Trim(),
				ItemPassQuestion2.Text.Trim()
				);
			if (result.success)
			{
				MessageBox.Show("注册成功。", "成功", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				Utility.Forms.FormClose(this);
			}
			else
			{
				MessageBox.Show("注册失败。" + result.message + "。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region void BtnClose_Click(object sender, EventArgs e)

		private void BtnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		#endregion



		#region void TextBox_KeyPress(object sender, KeyPressEventArgs e)

		private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == 13)
			{
				e.Handled = true;
				BtnRegister_Click(BtnRegister, new EventArgs());
			}

			if (e.KeyChar == 27)
			{
				e.Handled = true;
				BtnClose_Click(BtnClose, new EventArgs());
			}
		}

		#endregion
	}
}